package face.pay.common.enterprise.service.impl;

import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.sdk.OSSUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import face.pay.common.enterprise.service.IAlipayMachInfoService;
import face.pay.dao.*;
import face.pay.entity.*;
import face.pay.util.ResultMessage;
import face.pay.util.page.PageData;
import face.pay.util.page.PageParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class AlipayMachInfoServiceImpl implements IAlipayMachInfoService {


    @Autowired
    private AlipayMachInfoDao alipayMachInfoDao;


    @Autowired
    private UserInfoDao userInfoDao;


    @Autowired
    private EnterpriseInfoDao enterpriseInfoDao;


    @Autowired
    private FileInfoDao fileInfoDao;

    @Autowired
    private OemConfigInfoDao oemConfigInfoDao;


    /**
     * 查询进件资料
     *
     * @return
     */
    @Override
    public AlipayMachInfo queryAlipayMachInfo(UserInfo loginUser, Integer mcId) {
        AlipayMachInfo record = new AlipayMachInfo();
        record.setUserId(mcId);
        AlipayMachInfo alipayMachInfo = this.alipayMachInfoDao.queryAlipayMachInfo(record);
        if (alipayMachInfo == null) {
            AlipayMachInfo info = new AlipayMachInfo();
            info.setUserId(mcId);
            info.setOemId(loginUser.getOemId());
            info.setCreatedBy(loginUser.getId());
            UserInfo userinfo = userInfoDao.getById(mcId);
            UserInfo agency = userInfoDao.getById(userinfo.getRecommendId());
            info.setAgencyName(agency.getUserName());
            this.alipayMachInfoDao.insert(info);
            return info;
        } else {
            return alipayMachInfo;
        }
    }

    /**
     * 编辑支付宝进件资料
     *
     * @param alipayMachInfo
     * @param loginUser
     * @return
     */
    @Override
    public ResultMessage edit(AlipayMachInfo alipayMachInfo, UserInfo loginUser) {

        alipayMachInfo.setUpdatedBy(loginUser.getId());
        this.alipayMachInfoDao.update(alipayMachInfo);

        return ResultMessage.createSuccess();
    }


    /**
     * 分页查询进件申请
     *
     * @param pageParam
     * @param record
     * @param loginUser
     * @return
     */
    @Override
    public PageData queryData(PageParam pageParam, AlipayMachInfo record, UserInfo loginUser) {

        PageHelper.startPage(pageParam.getPageNo(), pageParam.getPageSize());

        record.setOemId(loginUser.getOemId());
        List<AlipayMachInfo> orders = this.alipayMachInfoDao.queryList(record);
        if (orders.size() > 0) {
            List<AlipayMachInfo> list = orders.stream().map(order -> {
                String s = order.getUpdatedTime().substring(0, 19);
                order.setUpdatedTime(s);
                return order;
            }).collect(Collectors.toList());
            PageInfo<AlipayMachInfo> pageInfo = new PageInfo<AlipayMachInfo>(orders);
            PageData<AlipayMachInfo> pageData = new PageData<AlipayMachInfo>(pageInfo.getTotal(), list);
            return pageData;
        } else {
            PageInfo<AlipayMachInfo> pageInfo = new PageInfo<AlipayMachInfo>(orders);
            PageData<AlipayMachInfo> pageData = new PageData<AlipayMachInfo>(pageInfo.getTotal(), orders);
            return pageData;
        }
    }

    /**
     * oem 处理进件资料
     *
     * @param alipayMachInfo
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage oemEdit(AlipayMachInfo alipayMachInfo, UserInfo loginUser) {

        alipayMachInfo.setUpdatedBy(loginUser.getId());
        if (StringUtils.isBlank(alipayMachInfo.getMessage())) {
            alipayMachInfo.setMessage(null);
        }
        if (alipayMachInfo.getStatus() == 4 && StringUtils.isBlank(alipayMachInfo.getMessage())) {
            alipayMachInfo.setMessage("请检查进件资料!");
        }
        if (alipayMachInfo.getStatus() == 3) {
            //处理成功
            alipayMachInfo.setMessage("处理成功");
            //更新支付宝费率
            EnterpriseInfo info = new EnterpriseInfo();
            info.setUserId(alipayMachInfo.getUserId());
            info.setAliFinalRate(alipayMachInfo.getAliFinalRate());
            info.setUpdatedBy(loginUser.getId());
            this.enterpriseInfoDao.update(info);
        }
        this.alipayMachInfoDao.update(alipayMachInfo);
        return ResultMessage.createSuccess();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultMessage fielUpload(byte[] fileBytes, String originalFilename, String keyName, Integer userId, UserInfo loginUser) {
        //获取oem商的oss配置信息
        OemConfigInfo oemConfig = this.oemConfigInfoDao.getByOemId(loginUser.getOemId());
        if (oemConfig == null) {
            return ResultMessage.createFail();
        }
        //生成fielInfo和fullname
        FileInfo fileInfo = new FileInfo(oemConfig.getOemId(), loginUser.getId(), originalFilename, "");
        String fullName = fileInfo.createFullName(oemConfig.getOemId());
        //推送到oss
        PutObjectResult putObjectResult = OSSUtils.putOSS(oemConfig.getEndPoint(), oemConfig.getAccessKeyId(), oemConfig.getAccessKeySecret(), oemConfig.getBucket(), fileInfo.getFullName(), fileBytes, false);
        if (null == putObjectResult) {
            return ResultMessage.createFail();
        }
        fileInfo.setCreatedBy(loginUser.getId());
        fileInfo.setUpdatedBy(loginUser.getId());
        this.fileInfoDao.insert(fileInfo);

        HashMap<String, Object> imageMap = new HashMap<>();
        imageMap.put("userId", userId);
        imageMap.put(keyName, fileInfo.getId());
        this.alipayMachInfoDao.updateImg(imageMap);
        HashMap<String, Object> map = new HashMap<>();
        map.put("id", fileInfo.getId());
        return ResultMessage.createSuccess(map);
    }
}
